package com.ext.portlet.registration.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;

import com.liferay.portal.PortalException;
import com.liferay.portal.SystemException;
import com.liferay.portal.events.ServicePreAction;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.search.SearchException;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.lar.PortletDataHandlerKeys;
import com.liferay.portal.model.Group;
import com.liferay.portal.model.Layout;
import com.liferay.portal.model.LayoutConstants;
import com.liferay.portal.model.LayoutSet;
import com.liferay.portal.model.LayoutTypePortlet;
import com.liferay.portal.model.User;
import com.liferay.portal.service.LayoutLocalServiceUtil;
import com.liferay.portal.service.LayoutSetLocalServiceUtil;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.util.FriendlyURLNormalizer;
import com.liferay.portal.util.PropsKeys;
import com.liferay.portal.util.PropsUtil;
import com.liferay.portal.util.PropsValues;
import com.liferay.portlet.enterpriseadmin.util.UserIndexer;

public class RegistrationActionUtil {	
	
	private static Log _log = LogFactoryUtil.getLog(RegistrationActionUtil.class);
	
	public static void addDefaultLayoutsByLAR(
			long userId, long groupId, boolean privateLayout, File larFile)
		throws PortalException, SystemException {

		Map<String, String[]> parameterMap = new HashMap<String, String[]>();

		parameterMap.put(
			PortletDataHandlerKeys.PERMISSIONS,
			new String[] {Boolean.TRUE.toString()});
		parameterMap.put(
			PortletDataHandlerKeys.PORTLET_DATA,
			new String[] {Boolean.TRUE.toString()});
		parameterMap.put(
			PortletDataHandlerKeys.PORTLET_DATA_CONTROL_DEFAULT,
			new String[] {Boolean.TRUE.toString()});
		parameterMap.put(
			PortletDataHandlerKeys.PORTLET_SETUP,
			new String[] {Boolean.TRUE.toString()});
		parameterMap.put(
			PortletDataHandlerKeys.USER_PERMISSIONS,
			new String[] {Boolean.FALSE.toString()});

		LayoutLocalServiceUtil.importLayouts(
			userId, groupId, privateLayout, parameterMap, larFile);
	}
	
	public static File getBlossomsDefaultLar() {
		ClassLoader classLoader = RegistrationActionUtil.class.getClassLoader();		
		Properties pro = new Properties();	
		InputStream inputStream = classLoader.getResourceAsStream("");
		File larFile = null;
		try {
			pro.load(inputStream);
			String larFilePath = PropsUtil.get("default.blossoms.public.layouts.lar");
			String str = PropsUtil.get("default.liferay.home");
			
			larFile = new File(str + larFilePath);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return larFile;
	}
	
	
	public static File getCampusDefaultLar() {
		ClassLoader classLoader = RegistrationActionUtil.class.getClassLoader();		
		Properties pro = new Properties();	
		InputStream inputStream = classLoader.getResourceAsStream("");
		File larFile = null;
		try {
			pro.load(inputStream);
			String larFilePath = PropsUtil.get("default.user.public.layouts.lar");
			String str = PropsUtil.get("default.liferay.home");
			
			larFile = new File(str + larFilePath);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return larFile;
	}
	
	//Code below by AYAZ starts
	
	public static void addDefaultUserPublicLayouts(User user)
	throws PortalException, SystemException {

	String publicLARFileName = PropsValues.DEFAULT_USER_PUBLIC_LAYOUTS_LAR;
	_log.info("Lar Name "+publicLARFileName);
	File publicLARFile = null;
	
	if (_log.isDebugEnabled()) {
		_log.debug("Reading public LAR file " + publicLARFileName);
	}

	if (Validator.isNotNull(publicLARFileName)) {
		publicLARFile = new File(publicLARFileName);

		if (!publicLARFile.exists()) {
			_log.error(
				"Public LAR file " + publicLARFile + " does not exist");

			publicLARFile = null;
		}
		else {
			if (_log.isDebugEnabled()) {
				_log.debug("Using public LAR file " + publicLARFileName);
			}
		}
	}
		
	Group userGroup = user.getGroup();

	if (publicLARFile != null) {
		addDefaultLayoutsByLAR(
			user.getUserId(), userGroup.getGroupId(), false, publicLARFile);
	}
	else {
		addDefaultUserPublicLayoutByProperties(
			user.getUserId(), userGroup.getGroupId());
	}
	}

	// For future user by AYAZ
	
	public static void addDefaultUserPublicLayoutByProperties(
			long userId, long groupId)
		throws PortalException, SystemException {

		String friendlyURL = getFriendlyURL(
			PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_FRIENDLY_URL);

		Layout layout = LayoutLocalServiceUtil.addLayout(
			userId, groupId, false, LayoutConstants.DEFAULT_PARENT_LAYOUT_ID,
			PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_NAME, StringPool.BLANK,
			StringPool.BLANK, LayoutConstants.TYPE_PORTLET, false, friendlyURL);

		LayoutTypePortlet layoutTypePortlet =
			(LayoutTypePortlet)layout.getLayoutType();

		layoutTypePortlet.setLayoutTemplateId(
			0, PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_TEMPLATE_ID, false);

		for (int i = 0; i < 10; i++) {
			String columnId = "column-" + i;
			String portletIds = PropsUtil.get(
				PropsKeys.DEFAULT_USER_PUBLIC_LAYOUT_COLUMN + i);

			String[] portletIdsArray = StringUtil.split(portletIds);

			layoutTypePortlet.addPortletIds(
				0, portletIdsArray, columnId, false);
		}

		LayoutLocalServiceUtil.updateLayout(
			layout.getGroupId(), layout.isPrivateLayout(), layout.getLayoutId(),
			layout.getTypeSettings());

		boolean updateLayoutSet = false;

		LayoutSet layoutSet = layout.getLayoutSet();

		if (Validator.isNotNull(
				PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_REGULAR_THEME_ID)) {

			layoutSet.setThemeId(
				PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_REGULAR_THEME_ID);

			updateLayoutSet = true;
		}

		if (Validator.isNotNull(
				PropsValues.
					DEFAULT_USER_PUBLIC_LAYOUT_REGULAR_COLOR_SCHEME_ID)) {

			layoutSet.setColorSchemeId(
				PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_REGULAR_COLOR_SCHEME_ID);

			updateLayoutSet = true;
		}

		if (Validator.isNotNull(
				PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_WAP_THEME_ID)) {

			layoutSet.setWapThemeId(
				PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_WAP_THEME_ID);

			updateLayoutSet = true;
		}

		if (Validator.isNotNull(
				PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_WAP_COLOR_SCHEME_ID)) {

			layoutSet.setWapColorSchemeId(
				PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_WAP_COLOR_SCHEME_ID);

			updateLayoutSet = true;
		}

		if (updateLayoutSet) {
			LayoutSetLocalServiceUtil.updateLayoutSet(layoutSet);
		}
	}
	//Code by AYAZ ends
	
	public static String getFriendlyURL(String friendlyURL) {
		friendlyURL = GetterUtil.getString(friendlyURL);

		return FriendlyURLNormalizer.normalize(friendlyURL);
	}
	
	public static User createUser(
            long companyId, String screenName, String firstName,
            String middleName, String lastName, boolean male, 
            int birthdayMonth, int birthdayDay, int birthdayYear, 
            String emailAddres,String jobTitle, String comments)
        throws Exception {
		
		long[] roleIds = {};
        long creatorUserId = 0;
        boolean autoPassword = false;
        String password1 = screenName;
        String password2 = password1;
        boolean autoScreenName = false;
        String emailAddress = emailAddres;
        String openId = StringPool.BLANK;
        Locale locale = Locale.US;
        int prefixId = 0;
        int suffixId = 0;
        
        long[] groupIds = null;

        long[] emptyLong = {};
        
        long[] userGroupIds = null;
        boolean sendEmail = false;
        ServiceContext serviceContext = null;

        User user = UserLocalServiceUtil.addUser(
            creatorUserId, companyId, autoPassword, password1, password2,
            autoScreenName, screenName, emailAddress, openId, locale, firstName,
            middleName, lastName, prefixId, suffixId, male, birthdayMonth,
            birthdayDay, birthdayYear, jobTitle, groupIds, emptyLong,
            roleIds, userGroupIds, sendEmail, serviceContext);
        
        user.setComments(comments);
        
        user = UserLocalServiceUtil.updateUser(user);
        
        try {
        		UserIndexer.updateUser(user);
        	}catch (SearchException se) {
        	 //
        	}
        
	 return user;
	
	}

}
